
require "framework.init"

local loop = z9.event_loop.new()
local socket = z9.socket
local packet = z9.packet

local clients = {} --客户端集合
local client_count = 0
local packet_count = 0

local server = socket.stream.ip4.listen(loop, "127.0.0.1", 8001,
    function(fd, err, strIp, intPort)
        print("新来客户端： fd:%d  ip:%s  port:%d \n", fd, strIp, intPort)
        --使用packet默认的decoder，解析粘包 。 4字节长度（不包含自身4字节，网络字节序）+数据
        local conn = socket.stream.new(fd, 4096, packet.decoder(65535) ) 
        if conn then
            clients[fd] = conn  --用fd做key
            client_count = client_count + 1
            conn:start(loop, function(data)
                if data then
                    for k, v in pairs(clients) do
                        packet_count = packet_count + 1
                        --[[
				        广播的时候一个套接口可能会连续发送很多包,
				        所以这里使用sendDelay尽量合并包一次性发送以提升性能
				        (注意这里没有地方调用flush,所以数据包会在下一次循环检测到套接口可写时执行实际的发送)
				        ]]--
                        v:sendDelay(data)
                    end
                else
                    print("client disconnected")
                    client_count = client_count - 1
                    conn:close()
                    clients[fd] = nil
                end
            end)
        end
    end
)

print("client   packet")
--显示，每一秒有多少client，发送的packet； 然后清零packet
local timer1 = loop:addTimer(1000, function()
    collectgarbage("collect")
	print(client_count, packet_count)
	packet_count = 0
end)

local timer2 = loop:addTimer(5, function()
    --发送紧急包
    for k, v in pairs(clients) do
        local buff = z9.buffer.new()
        local w = packet.writer(buff)
        w:writeStr("urgent")
        v:sendUrgent(buff)
    end
end)

print("server run")

if server then
    loop:watchSignal(z9.signal.SIGINT, function()
        print("Recv SIGINT stop server")
        loop:stop()
    end)
    loop:run()
end
